<template>
  <div class="singer-detail">
    <musicList :loading="loading"
               :pic="pic"
               :songs="songs"
               :title="title"
    ></musicList>
  </div>
</template>

<script>
import singerAPI from '../api/singer'
import songAPI from '../api/song'
import musicList from '../components/music-list/musicList'
import storage from 'good-storage'
import { SINGER_KEY } from '../assets/js/constant'

export default {
  name: 'singer-detail',
  components: { musicList },
  props: {
    singer: Object,
    default: () => {
      return {}
    }
  },
  computed: {
    computedSinger () {
      let ret = null
      const singer = this.singer
      // 如果是从父组件点击路由链接过来的, 直接把父组件传递的值赋给ret
      if (singer) {
        ret = singer
        // 如果是重新刷新页面而来的, 则从sessionStorage中获取, 并进行匹配判断
      } else {
        const cachedSinger = storage.session.get(SINGER_KEY)
        if (cachedSinger && cachedSinger.mid === this.$route.params.id) {
          ret = cachedSinger
        }
      }
      return ret
    },
    pic () {
      // 这个是给计算属性做一个缓存, 用到了多次
      const singer = this.computedSinger
      // && 效果做了一层判断
      return singer && singer.pic
    },
    title () {
      const singer = this.computedSinger
      return singer && singer.name
    },
    loading () {
      // 当数据为空的时候, 才会true, 才会出现加载效果
      return !this.songs.length
    }
  },
  data () {
    return {
      songs: []
    }
  },
  async created () {
    const data = this.computedSinger
    // data为空, 进入判断, 跳回上一级路由
    if (!data) {
      const path = this.$route.matched[0].path
      this.$router.push({
        path
      })
      return
    }
    console.log(data)
    const result = await singerAPI.getSingerDetail(data)
    // console.log(result)

    this.songs = await songAPI.processSongs(result.songs)
    // console.log(this.songs)
  }
}
</script>

<style lang="scss" scoped>
.singer-detail {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 10;

  background: $color-background;

}
</style>
